"""
Case Type   : 压缩整理shrink SQL
Case Name   : 使用shrink语法对Table执行压缩整理
Create At   : 2024-05-30
Owner       : @chen
Description :
    1.查看是否开启段页式
    2.创建表
    3.插入数据
    4.查询数据
    5.shrink操作
    6.查询数据
    7.清理环境
Expect      :
    1.查看是否开启段页式成功
    2.创建表成功
    3.插入数据成功
    4.查询数据成功
    5.shrink操作成功
    6.查询数据成功
    7.清理环境成功
History     : 
"""

import os
import unittest
from yat.test import Node
from testcase.utils.CommonSH import CommonSH
from testcase.utils.Logger import Logger

class Tools(unittest.TestCase):
    def setUp(self):
        self.log = Logger()
        self.dbuser_node = Node('PrimaryDbUser')
        self.commonsh = CommonSH()
        self.log.info(f"-----{os.path.basename(__file__)} start-----")

    def test_server_tools1(self):
        text = '--step1:查看是否开启段页式 expect:查询成功--'
        self.log.info(text)
        res = self.commonsh.execut_db_sql('show enable_segment;')
        self.log.info(res)
        self.assertIn('(1 row)', res, '执行失败' + text)

        text = '--step2:创建表 expect:创建成功--'
        self.log.info(text)
        sql_cmd = self.commonsh.execut_db_sql(
            f'''drop table if exists row_compression;create table 
            row_compression(id int, name varchar(10)) 
            with (compresstype=2, compress_chunk_size = 512, compress_level = 1);
            ''')
        self.log.info(sql_cmd)
        self.assertIn('CREATE TABLE', sql_cmd, '执行失败' + text)
        
        text = '--step3:插入数据 expect:插入数据成功--'
        self.log.info(text)
        insert_cmd = self.commonsh.execut_db_sql(
            f'''insert into row_compression values(generate_series(1,10), 
            'name'||generate_series(1,10));
            ''')
            
        self.log.info(insert_cmd)
        self.assertIn('INSERT 0 10', insert_cmd, '执行失败' + text)
        
        text = '--step4:查询数据 expect:查询数据成功--'
        self.log.info(text)
        select_cmd = self.commonsh.execut_db_sql('''select count(*) from row_compression;''')
        self.log.info(select_cmd)
        self.assertIn('10', select_cmd, '执行失败' + text)

        text = '--step5:shrink操作 expect:shrink操作成功--'
        self.log.info(text)
        shrink_cmd = self.commonsh.execut_db_sql('''shrink table row_compression;''')
        self.log.info(shrink_cmd)
        self.assertIn('SHRINK', shrink_cmd, '执行失败' + text)

        text = '--step6:查询数据 expect:查询数据成功--'
        self.log.info(text)
        select_cmd = self.commonsh.execut_db_sql('''select count(*) from row_compression;''')
        self.log.info(select_cmd)
        self.assertIn('10', select_cmd, '执行失败' + text)

    def tearDown(self):
        text = '--step7:清理环境 expect:清理环境成功--'
        self.log.info(text)
        drop_cmd = self.commonsh.execut_db_sql('''drop table if exists row_compression;''')
        self.log.info(drop_cmd)
        self.assertIn('DROP TABLE', drop_cmd, '执行失败' + text)
        self.log.info(f'-----{os.path.basename(__file__)} end-----')